package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.dao.BspsMchntKeyInfoMapper;
import cc.rengu.igas.bsps.common.dao.impl.BspsMchntKeyInfoMapperImpl;
import cc.rengu.igas.bsps.common.entity.MchntKeyInfo;
import cc.rengu.igas.bsps.common.enums.KeyAlgorithmTypeEnum;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.service.base.ManageService;
import cc.rengu.igas.bsps.facade.request.GenerateMchntKeyRequest;
import cc.rengu.igas.bsps.facade.response.GenerateMchntKeyResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.*;

/**
 * 生成商户密钥
 * Created by 王成 on 2020/3/25
 */
public class GenerateMchntKeyService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        GenerateMchntKeyRequest generateMchntKeyRequest = new GenerateMchntKeyRequest();
        ConvertUtil.convertOutput(generateMchntKeyRequest);
        return generateMchntKeyRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        GenerateMchntKeyRequest generateMchntKeyRequest = (GenerateMchntKeyRequest) request;
        GenerateMchntKeyResponse generateMchntKeyResponse = new GenerateMchntKeyResponse();
        BeanUtil.beanCopy(generateMchntKeyRequest, generateMchntKeyResponse);
        /* 参数合法性校验 */
        if (StringUtil.isEmptyOrNull(generateMchntKeyRequest.getUserId()) || StringUtil.isEmptyOrNull(generateMchntKeyRequest.getMchntNo()) ||
                StringUtil.isEmptyOrNull(generateMchntKeyRequest.getKeyType()) || StringUtil.isEmptyOrNull(generateMchntKeyRequest.getAlgorithmType())) {
            rglog.error("用户编号<{}>,商户号<{}>,密钥类型<{}>及算法类型<{}>不能为空!", generateMchntKeyRequest.getUserId(), generateMchntKeyRequest.getMchntNo(), generateMchntKeyRequest.getKeyType(), generateMchntKeyRequest.getAlgorithmType());
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        /* 根据算法类型生成商户密钥 */
        String mchntKeyValue;
        if (KeyAlgorithmTypeEnum.SHA1.getAlgorithmType().equals(generateMchntKeyRequest.getAlgorithmType())) {
            mchntKeyValue = RandomUtil.randomCharNumberString(32).toUpperCase();
        } else if (KeyAlgorithmTypeEnum.SM4.getAlgorithmType().equals(generateMchntKeyRequest.getAlgorithmType())) {
            mchntKeyValue = SM4Util.generateSm4Key(128).toUpperCase();
        } else {
            rglog.error("非法操作，不支持的密钥算法类型,algorithmType:<{}>", generateMchntKeyRequest.getAlgorithmType());
            throw new BizException(RespCodeEnum.ILLEGAL_OPERATION.getRespCode(), RespCodeEnum.ILLEGAL_OPERATION.getRespDesc());
        }
        /* 根据商户APPID及密钥类型查询是否存在密钥 */
        BspsMchntKeyInfoMapper bspsMchntKeyInfoMapper = new BspsMchntKeyInfoMapperImpl();
        String mchntAppId = StringUtil.isEmptyOrNull(generateMchntKeyRequest.getMchntAppId()) ? "APPID" : generateMchntKeyRequest.getMchntAppId();
        MchntKeyInfo mchntKeyInfo = bspsMchntKeyInfoMapper.selectBspsMchntKeyInfoByPrimaryKey(generateMchntKeyRequest.getHeader().getInstId(), generateMchntKeyRequest.getMchntNo(), mchntAppId, generateMchntKeyRequest.getKeyType());
        if (null == mchntKeyInfo) {
            mchntKeyInfo = new MchntKeyInfo();
            mchntKeyInfo.setInstId(generateMchntKeyRequest.getHeader().getInstId());
            mchntKeyInfo.setMchntNo(generateMchntKeyRequest.getMchntNo());
            mchntKeyInfo.setMchntAppId(mchntAppId);
            mchntKeyInfo.setKeyType(generateMchntKeyRequest.getKeyType());
            mchntKeyInfo.setAlgorithmType(generateMchntKeyRequest.getAlgorithmType());
            mchntKeyInfo.setKeyValue(mchntKeyValue);
            mchntKeyInfo.setKeyStatus(AppParamConstant.YES);
            mchntKeyInfo.setId(RandomUtil.getUUID().toUpperCase());
            mchntKeyInfo.setCreateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            int iReturnCode = bspsMchntKeyInfoMapper.insertBspsMchntKeyInfo(mchntKeyInfo);
            if (0 != iReturnCode) {
                rglog.error("登记商户密钥信息表失败,iReturnCode:<{}>", iReturnCode);
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }
        } else {
            mchntKeyInfo.setKeyValue(mchntKeyValue);
            int iReturnCode = bspsMchntKeyInfoMapper.updateBspsMchntKeyInfoById(mchntKeyInfo);
            if (0 != iReturnCode) {
                rglog.error("登记商户密钥信息表失败,iReturnCode:<{}>", iReturnCode);
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }
        }
        /* 组装应答报文 */
        generateMchntKeyResponse.setAlgorithmType(generateMchntKeyRequest.getAlgorithmType());
        generateMchntKeyResponse.setKeyValue(mchntKeyValue);
        BizResponse bizResponse = new BizResponse();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(generateMchntKeyResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        GenerateMchntKeyResponse generateMchntKeyResponse = (GenerateMchntKeyResponse) bizResponse.getResult();
        ConvertUtil.convertInput(generateMchntKeyResponse);
    }
}
